package com.smartlbs.baseframe.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.util.StringUtil;
import com.smartlbs.enums.SettingEnums;
import com.smartlbs.util.MD5Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Pattern;

public class HttpClientUtil {
	
	public static String doGet(String url, Map<String, String> param) {

		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();

			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);

			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String doGet(String url) {
		return doGet(url, null);
	}


	public static String doGets(String url,String function) {
		String ips = getips();
		
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();

		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
		
			URI uri = builder.build();
		 
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			   //设置代理IP，设置连接超时时间 、 设置 请求读取数据的超时时间 、 设置从connect Manager获取Connection超时时间、
			HttpHost httoHost =null;
			if(!StringUtil.isEmpty(ips)) {
				String[] split = ips.split(":");
				 httoHost = new HttpHost(split[0],Integer.valueOf(split[1]),"http");//代理Ip

			}

		  // HttpHost proxy = new HttpHost("60.211.218.78", 53281);
			    RequestConfig requestConfig = RequestConfig.custom()
			            .setProxy(httoHost)
			            .setConnectTimeout(1000000)
			            .setSocketTimeout(100000)
			            .setConnectionRequestTimeout(30000)
			            .build();
			  //  httpGet.setConfig(requestConfig);
		        CloseableHttpClient httpclient1 = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();

			// 执行请求
			response = httpclient1.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
				if(StringUtil.isEmpty(resultString)){
					ConfigFileUtils.getIplog();
					ConfigFileUtils.setIpslog(DateUtils.dateTostr(new Date()) +"数据未获取到  ip: "+ips +"\r\n  地址:" +url );
					String mail=new Date()+" 在查询"+function+" 时,未获取数据, 请检查相关数据是否有误, 查询地址为:"+url;
					MailUtils.Send(mail);
				}
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			ConfigFileUtils.getIplog();
			ConfigFileUtils.setIpslog(DateUtils.dateTostr(new Date()) +"  ip: "+ips +" 地址:"+url+"\r\n Exception:" +e);
			String mail=DateUtils.dateTostr(new Date())+" 在查询"+function+" 时,未获取数据, 请检查相关数据是否有误, 查询地址为:"+url;
			try {
				MailUtils.Send(mail);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	public static String getips() {
		Map<String, String> resultMap = new HashMap<>();
		String ip="";
		String ipstr = ConfigFileUtils.getPropertyString("ipCollection");
		if(!StringUtils.isEmpty(ipstr)){
			String[] ips = ipstr.split(",");
			Random r = new Random();
			int nextInt = r.nextInt(4);
			ip=ips[nextInt];
		}
		
		return ip;
	}
	/** 发送短信
	 * @param body
	 * @return
	 */
	public static String sendCode(String body) {
		String status="";
	    HttpClient client = HttpClients.createDefault();
	    
	    String appId=ConfigFileUtils.getPropertyString("phone_appId");
	    String accountId=ConfigFileUtils.getPropertyString("phone_accountId");
	    String authorToken=ConfigFileUtils.getPropertyString("phone_authorToken");
	   /* String appId="8a48b5515388ec15015398483496150c";
	    String accountId="8a48b5515388ec15015398467e8114f1";
	    String authorToken="03c26033689e4bfbb8820e59e793ee80";*/
	    
		try {
			Date date=new Date();
			String dateTostr = DateUtils.dateTostr(date, "yyyyMMddHHmmss");
			String md5Value = MD5Util.getMD5Value(accountId+authorToken+dateTostr);
			
			 String authorString=accountId+":"+dateTostr;
		        Base64 base64 = new Base64();

		        String base64Sign = base64.encodeToString(authorString.getBytes("UTF-8"));
		        
			
			URIBuilder builder = new URIBuilder("https://app.cloopen.com:8883/2013-12-26/Accounts/"+accountId+"/SMS/TemplateSMS?sig="+md5Value.toUpperCase()+"");
			URI uri = builder.build();
	        HttpPost post = new HttpPost(uri);
	       
	        post.setHeader("Content-Type", "application/json;charset=utf-8");
	        post.setHeader("Accept", "application/json");
	        post.setHeader("Authorization", "258");
	        post.setHeader("Authorization", base64Sign);
			
	        //设置请求体
	        post.setEntity(new StringEntity(body));
	        //获取返回信息
	        HttpResponse response = client.execute(post);
	        String string = response.toString();
	        if (response.getStatusLine().getStatusCode() == 200) {
	        	string = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
	         status = JSON.parseObject(string).getString("statusCode");
		} catch (Exception e) {
			e.printStackTrace();
		}
        return status;

	}
	
}
